package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Author：YH
 * @Description：消费者服务端作为调用者来调用支付接口8001 订单微服务调用支付微服务
 * @Date:Created in 2021/4/30 23:46
 */
@RestController
@Slf4j
public class OrderControl {

    //public final String PAYMENT_URL = "http://localhost:8001";

    //集群负载均衡
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    //发送请求 订单微服务调用支付微服务产生订单
    @GetMapping(value = "/consumer/payment/create")
    //@PostMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        log.info("payment" + payment);
        return restTemplate.postForObject(PAYMENT_URL + "payment/create", payment, CommonResult.class);
    }



    //测试地址  http://localhost/consumer/payment/get/1
    //订单微服务调用支付微服务读取订单
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        log.info("查询id为" + id);
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }


    //订单微服务调用支付微服务读取订单
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
        log.info("查询id为" + id);
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        log.info("查询id为" + forEntity.getBody());

        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        } else return new CommonResult<>(444, "getForEntity操作失败");
    }



    //测试地址 http://localhost/consumer/payment/lb
    @GetMapping(value = "/consumer/payment/lb")
    public String getPaymentLB() {

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if (instances == null || instances.size() < 0) {
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }
}
